package connect

import (
	"fmt"
	"net"
)

func ConnProcess(conn *net.Conn) {
	var buffer []byte = make([]byte, 1023)

	n, _ := (*conn).Read(buffer)

	//多个recover只会调用离panic最近的recover
	defer func() {
		fmt.Println("ConnProcess exit from address", (*conn).RemoteAddr().String())
		(*conn).Close()
		if err := recover(); err != nil {
			fmt.Println("连接崩溃:" + (*conn).RemoteAddr().String())
			fmt.Println(err)
			fmt.Println()
		}
	}()

	message := string(buffer[:n])
	fmt.Println("Receive identify message as ", message, " from raddresss", (*conn).RemoteAddr().String())
	if message == "server" {
		_, err := (*conn).Write([]byte("ok"))
		if err != nil {
			panic(err)
		}
		ServerConnProcess(conn)
	} else {
		_, err := (*conn).Write([]byte("ok"))
		if err != nil {
			panic(err)
		}
		ClientConnProcess(conn)
	}
}
